/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 * OrderSweepScurrySave
 * 赶房 {"whsk_Order_Sweep":{"room":"0411","wuserid":"S03","iuserid":"S03","remark":"123456"}}
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    Modal, Platform, BackHandler, ToastAndroid, TextInput
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './newScurry.Style'
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent";
import AntDesign from "react-native-vector-icons/AntDesign";
import FontAwesome from "react-native-vector-icons/FontAwesome"
import {
    COLOR_FOCUS,
    COLOR_HEADER_END,
    COLOR_HEADER_START,
    COLOR_THEME,
    FONT_COLOR_SUB_TITLE, FONT_COLOR_TITLE,
    FONT_SIZE_TITLE
} from "../../../constant/PHColors";
import BottomButtonView from "../../../component/BottomButtonView/BottomButtonView";
import Entypo from "react-native-vector-icons/Entypo";
import LinearGradient from "react-native-linear-gradient";
import {SaveRepairWorkOrder} from "../../job/WorkOrder/CreateRepairWorkOrderScreen/Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import {getScurryDefault,saveScurryOrder} from "./Actions"
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import {changeSweepOrderStatus} from "../../../component/BottomButtonView/Actions";

class newScurry extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `新建赶房`,
    });

    // 构造
    constructor(props) {
        super(props);

        let outjson = {};
        if(this.props.navigation.getParam("room") && this.props.navigation.getParam("room")!==""){
            this.props.navigation.getParam("room").split(',').map((item,index)=>{
                outjson[item] = {"whsk_Order_Sweep":{"room":item,"wuserid":"","iuserid":"","remark":""}}
            });
        }

        // 初始状态
        this.state = {
            checkModalVisible:false,
            outJson:outjson,         //{"0405":{"whsk_Order_Sweep":{"room":"0405","wuserid":"","iuserid":"","remark":""}},0406:{"whsk_Order_Sweep":{"room":"0406","wuserid":"","iuserid":"","remark":""}}}
            room:this.props.navigation.getParam("room")?this.props.navigation.getParam("room"):'',
            remark:'',
            returnModalVisible:false,           //是否放弃新建模态
            alertModalVisible:false,
            ifLocalPage:true,
            alertStr:{},
            alertData:{},
        };

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;


        if (nextProps.onGetScurryDefault !== this.props.onGetScurryDefault && nextProps.onGetScurryDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onGetScurryDefault.RETURN === ReturnStatus.Success) {
                let outjson = {};
                nextProps.onGetScurryDefault.data.map((item,index)=>{
                    outjson[item.room] = {"whsk_Order_Sweep":{"room":item.room,"wuserid":item.wuserid,"iuserid":item.iuserid,"remark":this.state.remark}}
                });
                this.setState({
                    room:this.state.room,
                    outJson:outjson,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onGetScurryDefault.MSG))
            }
        }

        if (nextProps.onSaveScurryOrder !== this.props.onSaveScurryOrder && nextProps.onSaveScurryOrder.fetchStatus === FetchStatus.Success) {
            if (nextProps.onSaveScurryOrder.RETURN === ReturnStatus.Success) {
                this.setState({
                    checkModalVisible:false,
                    returnModalVisible:false,
                    alertModalVisible:false,
                });

                this.saveTimes = this.saveTimes-1;
                if(this.saveTimes<=0){
                    this.props.navigation.state.params.callBack();
                }
            }else if(nextProps.onSaveScurryOrder.RETURN === '-10'){
                this.setState({
                    alertModalVisible:true,
                    alertData:nextProps.onSaveScurryOrder,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onSaveScurryOrder.MSG))
            }
        }

    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"work_Order_sweep":{"place":this.state.room}};
        dispatch(getScurryDefault(JSON.stringify(str)))
    }
    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.state.checkModalVisible===false&&this.props.navigation.isFocused()===true){
            this.setState({
                checkModalVisible:false,
                returnModalVisible:true,
                alertModalVisible:false,
            });
            return true;
        }else{
            return false;
        }
    };

    render() {
        let {dispatch} = this.props;
        let _this = this;
            return (
                <SafeAreaView style={styles.body}>
                    <ScrollView style={styles.body}>

                        <DividingLineViewComponent lineHeight={10}/>

                        {/* 地点 */}
                        <View style={{backgroundColor: '#FFF'}}>
                            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                this.props.navigation.navigate('RetrieveRoomsViewScreen',{multi:true,checkedRoom:this.state.room,callBack:(rooms_arr)=>{
                                    _this.props.navigation.navigate('newScurry');
                                    let rooms = []
                                    rooms_arr.map((item,index)=>{
                                        rooms.push(item.room)
                                    })

                                    this.getOutJson(rooms.join(','));
                                }});
                            }}>
                                <View style={styles.itemHeader}>
                                    <View style={styles.itemHeaderLeft}>
                                        <Text style={styles.itemHeaderText}>
                                            地点
                                        </Text>
                                    </View>
                                    <View style={styles.itemHeaderRight}>
                                        <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                    </View>
                                </View>
                            </TouchableOpacity>

                            <DividingLineViewComponent lineHeight={1}/>

                            <View style={{margin: 15,flexDirection:'row'}}>
                                <TextInput
                                    placeholder={'选择地点'}
                                    style={{
                                        fontSize: 16,
                                        padding: 0,
                                        color:(this.state.room===""||typeof (this.state.room)==='undefined')?'#f1f1f1':'#000000',
                                    }}
                                    numberOfLines={1}
                                    underlineColorAndroid={'transparent'}
                                    onChangeText={text=>{

                                    }}
                                    defaultValue = {this.state.room}
                                    editable = {false}
                                />
                                {
                                    (this.state.room!==""&&typeof (this.state.room)!=='undefined') && (
                                        <View style={styles.itemHeaderRight}>
                                            <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{
                                                this.getOutJson('');
                                            }}/>
                                        </View>
                                    )
                                }
                            </View>
                        </View>

                        <DividingLineViewComponent lineHeight={10}/>

                        {/* 清洁人 */}
                        {
                            <View style={{backgroundColor: '#FFF'}}>
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    if(this.state.room.split(',').length>1){

                                    }else{

                                    }
                                }}>
                                    <View style={styles.itemHeader}>
                                        <View style={styles.itemHeaderLeft}>
                                            <Text style={styles.itemHeaderText}>
                                                人员安排
                                            </Text>
                                        </View>
                                        <View style={styles.itemHeaderRight}>
                                            {/*<AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>*/}
                                        </View>
                                    </View>
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                {
                                    this.show_order()
                                }

                            </View>
                        }

                        {/* 查房主管 */}
                        {/*{*/}
                            {/*<View style={{backgroundColor: '#FFF'}}>*/}
                                {/*<TouchableOpacity activeOpacity={0.8} onPress={() => {*/}

                                {/*}}>*/}
                                    {/*<View style={styles.itemHeader}>*/}
                                        {/*<View style={styles.itemHeaderLeft}>*/}
                                            {/*<Text style={styles.itemHeaderText}>*/}
                                                {/*查房主管*/}
                                            {/*</Text>*/}
                                        {/*</View>*/}
                                        {/*<View style={styles.itemHeaderRight}>*/}
                                            {/*<AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>*/}
                                        {/*</View>*/}
                                    {/*</View>*/}
                                {/*</TouchableOpacity>*/}

                                {/*<DividingLineViewComponent lineHeight={1}/>*/}

                                {/*<View style={{margin: 15,flexDirection:'row'}}>*/}
                                    {/*<TextInput*/}
                                        {/*placeholder={'选择查房主管'}*/}
                                        {/*style={{*/}
                                            {/*fontSize: 16,*/}
                                            {/*padding: 0,*/}
                                            {/*color:(this.state.room!=='' && this.state.room.split(',').length === 1 && this.state.outJson[this.state.room]['iuserid'] !== '')?'#f1f1f1':'#000000',*/}
                                        {/*}}*/}
                                        {/*numberOfLines={1}*/}
                                        {/*underlineColorAndroid={'transparent'}*/}
                                        {/*onChangeText={text=>{*/}

                                        {/*}}*/}
                                        {/*defaultValue = {''}*/}
                                        {/*editable = {false}*/}
                                    {/*/>*/}
                                    {/*{*/}
                                        {/*(this.state.room!=='' && this.state.room.split(',').length === 1 && this.state.outJson[this.state.room]['iuserid'] !== '') && (*/}
                                            {/*<View style={styles.itemHeaderRight}>*/}
                                                {/*<AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{*/}

                                                {/*}}/>*/}
                                            {/*</View>*/}
                                        {/*)*/}
                                    {/*}*/}

                                {/*</View>*/}

                            {/*</View>*/}
                        {/*}*/}

                        <DividingLineViewComponent lineHeight={10}/>

                        {
                            <View style={{backgroundColor: '#FFF'}}>
                                <View style={styles.itemHeader}>
                                    <View style={styles.itemHeaderLeft}>
                                        <Text style={styles.itemHeaderText}>
                                            备注信息
                                        </Text>
                                    </View>
                                    <View style={styles.itemHeaderRight}>
                                        <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                                            {this.state.remark.length}
                                            <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                                                /100
                                            </Text>
                                        </Text>
                                    </View>
                                </View>

                                <DividingLineViewComponent lineHeight={1}/>

                                <View style={{margin: 15, height: 120}}>
                                    <TextInput
                                        placeholder={'输入备注信息'}
                                        multiline={true}
                                        maxLength={100}
                                        style={{
                                            fontSize: 16,
                                            padding: 0,
                                            height:120,
                                            textAlignVertical: "top",
                                            lineHeight:25,
                                        }}
                                        underlineColorAndroid={'transparent'}
                                        onChangeText={text => {
                                            if(text.length>100){
                                                text = text.substring(0,100)
                                            }
                                            let outJson = this.state.outJson;
                                            for (let room_index in outJson){
                                                outJson[room_index]['whsk_Order_Sweep']['remark']=text;
                                            }
                                            this.setState({
                                                remark:text,
                                                outJson:outJson,
                                            })
                                        }}
                                    />
                                </View>
                            </View>
                        }


                    </ScrollView>

                    <BottomButtonView title={'完成'} onSubmitClick={() => {
                        this._onCheck()
                    }}/>

                    <Modal visible={this.state.checkModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                        <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                            <View style={styles.checkModalBody}>
                                <View style={styles.checkModalHeader}>
                                    <Text style={styles.checkModalHeaderText}>
                                        确认下单？
                                    </Text>
                                </View>
                                <View style={styles.checkModalCenter}>
                                    <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                        this.setState({
                                            checkModalVisible:false,
                                        })
                                    }}>
                                        <Text style={{color:'black'}}>
                                            取消
                                        </Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                        this._onSubmitClick()
                                    }}>
                                        <Text style={{color:'white'}}>
                                            下单
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    </Modal>

                    <Modal visible={this.state.returnModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={()=> this.onRequestClose()}>
                            <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                                <View style={styles.checkModalBody}>
                                    <View style={styles.checkModalHeader}>
                                        <Text style={styles.checkModalHeaderText}>
                                            放弃新建工单么？
                                        </Text>
                                    </View>
                                    <View style={styles.checkModalCenter}>
                                        <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                            this.setState({
                                                returnModalVisible:false,
                                            });
                                            this.props.navigation.goBack();
                                        }}>
                                            <Text style={{color:'black'}}>
                                                放弃
                                            </Text>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                            this.setState({
                                                returnModalVisible:false,
                                            })
                                        }}>
                                            <Text style={{color:'white'}}>
                                                继续新建
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>

                    {/*alert-10模态框*/}
                    <Modal visible={this.state.alertModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            this.onRequestClose();
                        }}>
                            <View style={styles.checkmodalContainer} >
                                <View style={styles.checkModalBody}>
                                    <View style={styles.checkModalHeader}>
                                        <Text style={styles.checkModalHeaderText}>
                                            {this.state.alertData.MSG}
                                        </Text>
                                    </View>
                                    <View style={styles.checkModalCenter}>
                                        <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                            this.setState({
                                                alertModalVisible:false,
                                            })
                                        }}>
                                            <Text style={{color:'black',fontSize:20}}>
                                                取消
                                            </Text>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                            this.setState({
                                                alertModalVisible:false,
                                            })
                                            let str = this.state.alertStr;
                                            str.arg={};
                                            str.arg[this.state.alertData.checkbox]='yes';
                                            dispatch(saveScurryOrder(JSON.stringify(str)));
                                        }}>
                                            <Text style={{color:'white',fontSize:20}}>
                                                继续
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>
                </SafeAreaView>
            )
    }

    show_order(){
        let _this = this;
        let html_arr  = [];

        for(let key in this.state.outJson){
            let json = this.state.outJson[key]['whsk_Order_Sweep'];
            let html = (
                <View style={{flex: 1,flexDirection:'row',height:40,}}>
                    <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                        <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                            {json.room}
                        </Text>
                    </View>
                    <View style={{width:(SCREEN_WIDTH-80)/2,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                        {
                            (json.wuserid==='')
                            ?
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                                            _this.props.navigation.navigate('newScurry');
                                            this.state.outJson[key]['whsk_Order_Sweep'].wuserid = users;
                                            this.setState({
                                                outJson:this.state.outJson,
                                            })
                                        }})
                                    }}>
                                        <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_SUB_TITLE}}>
                                                请选择
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                            :
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:json.wuserid,callBack:(users)=>{
                                            _this.props.navigation.navigate('newScurry');
                                            this.state.outJson[key]['whsk_Order_Sweep'].wuserid = users;
                                            this.setState({
                                                outJson:this.state.outJson,
                                            })
                                        }})
                                    }}>
                                        <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                                {json.wuserid}
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                        }
                    </View>
                    <View style={{width:(SCREEN_WIDTH-80)/2,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                        {
                            (json.iuserid==='')
                                ?
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                                            _this.props.navigation.navigate('newScurry');
                                            this.state.outJson[key]['whsk_Order_Sweep'].iuserid = users;
                                            this.setState({
                                                outJson:this.state.outJson,
                                            })
                                        }})
                                    }}>
                                        <View style={{flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_SUB_TITLE}}>
                                                全部客房主管
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                                :
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:json.iuserid,callBack:(users)=>{
                                            _this.props.navigation.navigate('newScurry');
                                            this.state.outJson[key]['whsk_Order_Sweep'].iuserid = users;
                                            this.setState({
                                                outJson:this.state.outJson,
                                            })
                                        }})
                                    }}>
                                        <View style={{flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                                {json.iuserid}
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                        }
                    </View>
                </View>
            );
            let html1 = (
                <DividingLineViewComponent lineHeight={1}/>
            );
            html_arr.push(html1);
            html_arr.push(html);
        }
        if(html_arr.length>0){
            let title_html = (
                <View style={{flex: 1,flexDirection:'row',height:40}}>
                    <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center',height:40}}>
                        <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                            房号
                        </Text>
                    </View>
                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                            _this.props.navigation.navigate('newScurry');
                            let newOutJson = this.state.outJson;
                            for(let json in newOutJson){
                                newOutJson[json]['whsk_Order_Sweep'].wuserid = users;
                            }
                            this.setState({
                                outJson:newOutJson,
                            })
                            }})
                    }}>
                        <View style={{width:(SCREEN_WIDTH-80)/2,flexDirection:'row',alignItems:'center',justifyContent:'center',height:40}}>
                            <View style={{flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                    清洁人
                                    <FontAwesome name={'question-circle'} size={18} style={{color: COLOR_FOCUS,marginLeft: 2,}}/>
                                </Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                                _this.props.navigation.navigate('newScurry');
                                let newOutJson = this.state.outJson;
                                for(let json in newOutJson){
                                    newOutJson[json]['whsk_Order_Sweep'].iuserid = users;
                                }
                                this.setState({
                                    outJson:newOutJson,
                                })
                            }})
                    }}>
                        <View style={{width:(SCREEN_WIDTH-80)/2,flexDirection:'row',alignItems:'center',justifyContent:'center',height:40}}>
                            <View style={{flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                    检查人
                                    <FontAwesome name={'question-circle'} size={18} style={{color: COLOR_FOCUS,marginLeft: 2,}}/>
                                </Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
            )
            html_arr.splice(0,0,title_html)
        }

        return html_arr;
    };

    //检查数据格式
    _onCheck=()=>{
        this.setState({
            checkModalVisible:true,
        })
    };

    getOutJson=(rooms)=>{
        let {dispatch} = this.props;

        let str = {"work_Order_sweep":{"place":rooms}}
        this.state.room = rooms;
        dispatch(getScurryDefault(JSON.stringify(str)))

    };

    //确认提交
    _onSubmitClick=()=>{
        console.log(JSON.stringify(this.state.outJson))

        this.saveTimes=0;
        for(let json in this.state.outJson){
            this.saveTimes=this.saveTimes+1;
        }

        for(let json in this.state.outJson){
            let {dispatch} = this.props;
            this.state.alertStr = this.state.outJson[json];
            dispatch(saveScurryOrder(JSON.stringify(this.state.outJson[json])));
        }
        // let outJson = {"qms_repair":str,"arg":{"self_report":"true"}};
        // let {dispatch} = this.props;
        // dispatch(SaveRepairWorkOrder(JSON.stringify(outJson)));
    }

    onRequestClose(){
        this.setState({
            checkModalVisible:false,
            returnModalVisible:false,
            alertModalVisible:false,
        })
    }
}

const props = state => {
    return {
        onGetScurryDefault:state.onGetScurryDefault,
        onSaveScurryOrder:state.onSaveScurryOrder,
    }
}

export default newScurry = connect(props)(newScurry);